#include "ListView.h"
#include "base/TrueTypeFont.h"
#include "base/Utility.h"
#include "BSUtility.h"

#define SetAttr(AttrName) SetAttribute(AttrName, ele->Attribute(AttrName));
void ListView::ParseXmlElement(TiXmlElement* ele)
{
    this->name = ele->Attribute("name");
    SetAttr("pos")
        SetAttr("size")
}

bool ListView::SetAttribute(const char* attrName, const char* attrVal)
{
    if (attrVal == nullptr) return false;
    if (strcmp(attrName, "pos") == 0)
    {
        int x, y;
        sscanf_s(attrVal, "%d,%d", &x, &y);
        pos.x = x;
        pos.y = y;
        return true;
    }
    else   if (strcmp(attrName, "size") == 0)
    {
        int x, y;
        sscanf_s(attrVal, "%d,%d", &x, &y);
        size.x = x;
        size.y = y;
        return true;
    }

    return false;
}

void ListView::OnDraw()
{
    DrawBorder();
    for (int i = 0;i < items.size();i++)
    {
        std::wstring wstr = Utility::ConvertToWstring(items[i]);
        TrueTypeFont* ttf = TrueTypeFont::GetInst();
        ttf->drawText(const_cast<wchar_t*>(wstr.data()), pos.x.val, pos.y.val + (i + 1) * itemHeight,zIndex.val, size.x.val, size.y.val);
    }
    int curY = 0;
    for (int i = 0;i < childs.size();i++)
    {
        childs[i].second->pos.x.val = pos.x.val;
        childs[i].second->pos.y.val = pos.y.val + curY;
        childs[i].second->Draw();
        curY += childs[i].second->size.y.val;
        /*  std::wstring wstr = Utility::ConvertToWstring(items[i]);
          TrueTypeFont* ttf = TrueTypeFont::GetInst();
          ttf->drawText(const_cast<wchar_t*>(wstr.data()), pos.x.val, pos.y.val + (i + 1) * itemHeight, size.x.val, size.y.val);*/
    }
}

void ListView::onMouseButtonDown(int button, int x, int y)
{
    Vec2vbi point;
    point.x.val = x;
    point.y.val = y;
    //items.push_back("a");
    for (int i = 0;i < childs.size();i++)
    {
        if (BSUtility::HitTest(point, childs[i].second->pos, childs[i].second->size).val)
        {
            childs[i].second->onMouseButtonDown(button, x, y);
        }
    }

}

void ListView::onMouseButtonUp(int button, int x, int y)
{
    Vec2vbi point;
    point.x.val = x;
    point.y.val = y;
    //items.push_back("a");
    for (int i = 0;i < childs.size();i++)
    {
        if (BSUtility::HitTest(point, childs[i].second->pos, childs[i].second->size).val)
        {
            childs[i].second->onMouseButtonUp(button, x, y);
        }
    }
}

BlueprintScriptLibrary::Class* ListView::GetClass()
{
    return nullptr;
}
